//
//  XDRecommendViewController.m
//  Le way walkers
//
//  Created by POP-mac on 15/5/13.
//  Copyright (c) 2015年 LTXZ. All rights reserved.
//

#import "XDRecommendViewController.h"
#import "XDReconmmendTableViewCell.h"
#import "XDDetailsViewController.h"
#import "NetworkHandle.h"
#import "UIImageView+WebCache.h"
#import "XDRecommendWebViewController.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "XDRecommend.h"
#import "XDRecommendDateBaseManager.h"
@interface XDRecommendViewController () <UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic,retain) UITableView *tableView;
@property (nonatomic,retain) UICollectionView *collectionView;
@property (nonatomic,retain) UICollectionViewCell *cell;
@property (nonatomic,retain) UIPageControl *pageControl;
@property (nonatomic,retain) NSMutableArray *Arr;
@property (nonatomic,retain) NSMutableArray *Arr1;
@property (nonatomic,retain) UIImageView *imageView;
@property (nonatomic,assign) NSInteger num;
@property (nonatomic,assign) NSInteger i;
@property (nonatomic,retain) NSString *aaa;
@property (nonatomic,retain) NSString *bbb;
@property (nonatomic,assign) BOOL booll ;
@property (nonatomic,retain) MBProgressHUD *Hud;
@property (nonatomic,retain) XDRecommendDateBaseManager *dbManager;
@property (nonatomic, retain) UIImageView *gifImageView;
@end

@implementation XDRecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.dbManager = [XDRecommendDateBaseManager shareInstance];
    //打开数据库
    [_dbManager openDB];

    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"推荐";
//    [self createMBProgressHUD];
    [self yangTuo];
//    [self createMBProgressHUD];
    
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(star) userInfo:nil repeats:YES];
    self.i = 0;
    _booll = YES;

   
    
}




- (void)star
{
    self.num = self.num % (_Arr1.count - 2) + 1;
    _collectionView.contentOffset = CGPointMake(self.view.frame.size.width * self.num, 0);
    _pageControl.currentPage = self.num-1;
   // NSLog(@"%ld", self.num);
}




- (void)createTableView
{
    self.tableView = [[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain]autorelease];
    _tableView.delegate = self;
    _tableView.dataSource =self;
    _tableView.rowHeight = (self.view.frame.size.width-10)/4*3+10;
    [_tableView addHeaderWithCallback:^{
        [self.tableView reloadData];
        [self getData];
    }];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [_tableView addFooterWithCallback:^{
        [self getData1];
    }];
}




- (void)createCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[[UICollectionViewFlowLayout alloc]init]autorelease];
    //item的大小
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height/3+20);
    //横向滑动(系统默认为竖向滑动)
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //item最小行间距
    flowLayout.minimumLineSpacing = 0;
    
    self.collectionView = [[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height/3+20) collectionViewLayout:flowLayout]autorelease];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsHorizontalScrollIndicator = NO;
    //让图片显示第二张(偏移量)
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
    //是否可以整页翻动
    _collectionView.pagingEnabled = YES;
    //关闭边缘弹动
    _collectionView.bounces = NO;
    _tableView.tableHeaderView = _collectionView;
    //collectionView创建时 必须先注册一个cell
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    //页码控制器
    self.pageControl = [[[UIPageControl alloc]initWithFrame:CGRectMake( self.view.frame.size.width/2-50, self.view.frame.size.height/3-10, 100, 20)]autorelease];
    //设置需要几个圆点
    _pageControl.numberOfPages = _Arr1.count-2;
    //设置当前亮点在第几位
    _pageControl.currentPage = 0;
    //背景颜色
//    [_pageControl setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.2]];
    //圆角
    [_pageControl.layer setCornerRadius:8];
    // 未选中圆点的颜色
    //_pageControl.pageIndicatorTintColor = [UIColor redColor];
    //当前圆点的颜色
    _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    //绑定响应事件
    [_pageControl addTarget:self action:@selector(page:) forControlEvents:UIControlEventValueChanged];
    [_tableView addSubview:_pageControl];
}




//pageControl绑定响应
- (void)page:(UIPageControl *)page
{
    _collectionView.contentOffset = CGPointMake(_pageControl.currentPage * self.view.frame.size.width ,0);
}




//轮播图循环判断
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _pageControl.currentPage = _collectionView.contentOffset.x/self.view.frame.size.width-1;
    if (_collectionView.contentOffset.x == (_Arr1.count - 1) *self.view.frame.size.width ) {
        _collectionView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
        _pageControl.currentPage = 0;
    }
    else if (_collectionView.contentOffset.x == 0){
        _collectionView.contentOffset = CGPointMake(self.view.frame.size.width *(_Arr1.count - 2), 0);
        _pageControl.currentPage = _Arr1.count - 3;
   }
}




//collectionView控制分区个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    //NSLog(@"%ld", _Arr1.count);
    return _Arr1.count;
}




- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    self.imageView = [[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height/3+20)]autorelease];
    self.num = indexPath.row;
    [_imageView sd_setImageWithURL:[NSURL URLWithString:[[_Arr1 objectAtIndex:indexPath.row] objectForKey:@"image_url"]]];
    //NSLog(@"%@", [[_Arr1 objectAtIndex:indexPath.row] objectForKey:@"image_url"]);
    [_cell.contentView addSubview:_imageView];
//    if (indexPath.row == 0) {
//        self.imageView.image = [UIImage imageNamed:@"1.jpg"];
//        [_cell.contentView addSubview:self.imageView];
//    }else if (indexPath.row == 1){
//        self.imageView.image = [UIImage imageNamed:@"2.jpg"];
//        [_cell.contentView addSubview:self.imageView];
//    }else if (indexPath.row == 2){
//        self.imageView.image = [UIImage imageNamed:@"3.jpg"];
//        [_cell.contentView addSubview:self.imageView];
//    }else if (indexPath.row == 3){
//        self.imageView.image = [UIImage imageNamed:@"4.jpg"];
//        [_cell.contentView addSubview:self.imageView];
//    }else if (indexPath.row == 4){
//        self.imageView.image = [UIImage imageNamed:@"5.jpg"];
//        [_cell.contentView addSubview:self.imageView];
//    }else if (indexPath.row == 5){
//        self.imageView.image = [UIImage imageNamed:@"1.jpg"];
//        [_cell.contentView addSubview:self.imageView];
//    }else if (indexPath.row == 6){
//        self.imageView.image = [UIImage imageNamed:@"2.jpg"];
//        [_cell.contentView addSubview:self.imageView];
//    }
    return _cell;
}




//tableView控制分区个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _Arr.count;
}




//collectionView Push详情页面
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    XDRecommendWebViewController *Web = [[[XDRecommendWebViewController alloc]init]autorelease];
    Web.str = [[_Arr1 objectAtIndex:indexPath.row] objectForKey:@"html_url"];
    
    [self.navigationController pushViewController:Web animated:YES];
}




//tableView Push详情页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //点击事件
    //点击效果取消 徐+
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    XDDetailsViewController *details = [[[XDDetailsViewController alloc]init]autorelease];
    details.ids = [NSString stringWithFormat:@"%@", [self.Arr[indexPath.row] ids]];
    details.name = [self.Arr[indexPath.row] name];
    NSLog(@"%@", details.ids);
    details.popular_place_str = [self.Arr[indexPath.row]popular_place_str];
    details.first_day =  [self.Arr[indexPath.row]first_day];
    details.day_count = [self.Arr[indexPath.row]day_count];
    details.cover_image = [self.Arr[indexPath.row]cover_image];
    [self.navigationController pushViewController:details animated:YES];
    self.tabBarController.tabBar.hidden = YES;
}




-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XDReconmmendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (!cell) {
        cell = [[[XDReconmmendTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"]autorelease];
    }
    cell.recommend = _Arr[indexPath.row];
   
    
    return cell;
}




//网络数据解析
-(void)getData
{
    [NetworkHandle getDataWithURL:@"http://api.breadtrip.com/v5/index" completion:^(id result) {
        
        self.aaa = [NSString stringWithFormat:@"%@",[result objectForKey:@"next_start"]];
        self.Arr = [NSMutableArray array];
        self.Arr1 = [NSMutableArray array];
        NSMutableArray *arr1 = [NSMutableArray array];
        NSMutableArray *arr2 = [NSMutableArray array];
        NSArray *arr = [result objectForKey:@"elements"];
        for (NSMutableDictionary *dic1 in arr) {
            //            NSLog(@"%@", [dic1 objectForKey:@"type"]);
            if ([[dic1 objectForKey:@"type"] integerValue] == 4) {
                [arr1 addObject:dic1];
            }else if ([[dic1 objectForKey:@"type"] integerValue] == 1){
                [arr2 addObject:dic1];
            }
        }
        //tableview
        for (NSDictionary *dic in arr1) {
            XDRecommend *xd = [[[XDRecommend alloc]init]autorelease];
            [xd setValuesForKeysWithDictionary:[[dic objectForKey:@"data"] objectAtIndex:0]];
            [self.Arr addObject:xd];
            
        }
        //轮播图
        
        self.Arr1 = [[[arr2 objectAtIndex:0] objectForKey:@"data"] objectAtIndex:0];
        //插入图片
        [_Arr1 insertObject:[_Arr1 lastObject] atIndex:0];
        [_Arr1 insertObject:[_Arr1 objectAtIndex:1] atIndex:_Arr1.count];
       
        [self createTableView];
        [self createCollectionView];
        
        //隐藏
//        [self.Hud hide:YES];
        [self.gifImageView stopAnimating];
        self.gifImageView.hidden = YES;
        [_pageControl setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.2]];
    }];
}




-(void)getData1
{
    if (_booll == NO) {
        return;
    }
    _i++;
    NSString *str = @"http://api.breadtrip.com/v5/index/?next_start=";
    NSString *str2    = [NSString stringWithFormat:@"%@%@",str,self.aaa];
    if (_i >= 2 ) {
        str2 = [NSString stringWithFormat:@"%@%@",str,self.bbb];
    }
    NSLog(@"%@",str2);
    NSLog(@"%ld",(long)_i);
    _booll = NO;
    [NetworkHandle getDataWithURL:str2 completion:^(id result) {
        self.bbb = [NSString stringWithFormat:@"%@",[result objectForKey:@"next_start"]];
        NSMutableArray *arr1 = [NSMutableArray array];
        NSArray *arr = [result objectForKey:@"elements"];
        for (NSMutableDictionary *dic1 in arr) {
            //            NSLog(@"%@", [dic1 objectForKey:@"type"]);
            if ([[dic1 objectForKey:@"type"] integerValue] == 4) {
                [arr1 addObject:dic1];
            }
        }
        
        //tableview
        for (NSDictionary *dic in arr1) {
            XDRecommend *xd = [[XDRecommend alloc]init];
            [xd setValuesForKeysWithDictionary:[[dic objectForKey:@"data"] objectAtIndex:0]];
            [self.Arr addObject:xd];
            [xd release];
        }
        //结束刷新
        [self.tableView footerEndRefreshing];
        [self.tableView headerEndRefreshing];
        //重新获取数据
        [self.tableView reloadData];

        _booll = YES;
    }];
}


- (void)yangTuo
{
    [self getData];
    self.gifImageView.hidden = NO;
    self.gifImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 40, self.view.frame.size.height / 2 - 50, 80, 100)];
    NSArray *gifArray = [NSArray arrayWithObjects:[UIImage imageNamed:@"cao1.png"],
                         [UIImage imageNamed:@"cao2.png"],
                         [UIImage imageNamed:@"cao3.png"],
                         [UIImage imageNamed:@"cao4.png"],
                         [UIImage imageNamed:@"cao5.png"],
                         [UIImage imageNamed:@"cao6.png"],
                         [UIImage imageNamed:@"cao7.png"],
                         [UIImage imageNamed:@"cao8.png"],
                         [UIImage imageNamed:@"cao9.png"],
                         [UIImage imageNamed:@"cao10.png"],nil];
    self.gifImageView.animationImages = gifArray; //动画图片数组
    self.gifImageView.animationDuration = 0.8; //执行一次完整动画所需的时长
    self.gifImageView.animationRepeatCount = 10000;  //动画重复次数
    [self.gifImageView startAnimating];
    [self.view addSubview:self.gifImageView];
    [self.gifImageView release];
}




//加载小菊花
-(void)createMBProgressHUD
{
    self.Hud = [[[MBProgressHUD alloc]initWithView:self.view]autorelease];
    [self.view addSubview:_Hud];
    _Hud.labelText = @"正在加载";
    [self.view addSubview:self.Hud];
    //如果设置此属性则当前的view置于后台
    self.Hud.dimBackground = YES;
    [self getData];
    //一直显示
    [self.Hud show:YES];
    
    
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
